﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractMes;
using HamcoWcs.Contract.ContractPcon;
using HamcoWcs.Contract.ContractSrm;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.BaseConfigs;
using HamcoWcs.Entitys.DeviceErrors;
using HamcoWcs.Entitys.DeviceMsgQueues;
using HamcoWcs.Entitys.Logs;
using HamcoWcs.Entitys.Logss;
using HamcoWcs.Entitys.MainTasks;
using HamcoWcs.Entitys.MesMsgQueues;
using HamcoWcs.Entitys.PalletInfos;
using HamcoWcs.Entitys.WcsLocations;
using HamcoWcs.Models.Common;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.DeviceMsgQueues;
using HamcoWcs.Models.DeviceMsgs;
using HamcoWcs.Models.DeviceMsgs.SrmMsgs;
using HamcoWcs.Models.Devices;
using HamcoWcs.Models.ForeEndModels.UITasks;
using HamcoWcs.Models.MainTasks;
using HamcoWcs.Models.MesMsgQueues;
using HamcoWcs.Models.Monitors;
using HamcoWcs.Models.TibcoMessage;
using HamcoWcs.Models.TibcoMessage.Items;
using HamcoWcs.Service.Common;
using HamcoWcs.Service.Mes.Parsers;
using HamcoWcs.Workers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.XWPF.UserModel;
using Qin.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using Formatting = Newtonsoft.Json.Formatting;
using ValidationType = NPOI.SS.UserModel.ValidationType;
using XmlHelper = System.Xml.XmlHelper;

namespace HamcoWcs.Main.Controllers
{
    /// <summary>
    /// 测试接口
    /// </summary>
    public class ATestController : BasicController
    {

        #region [Constructor]

        private readonly IPathService _pathService;
        private readonly IMonitorBaseService _monitorBaseService;
        private readonly IMesBaseService _mesBaseService;
        private readonly ILocationService _locationService;
        private readonly IMesCommunicateService _mesCommunicateService;
        private readonly IPconBaseService _pconBaseService;
        private readonly ISrmTaskFinderFactory _srmTaskFinderFactory;
        private readonly AutomaticStorageInfo _asrs;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ILoggerService _loggerService;
        private readonly IBaseConfigService _config;

        /// <summary>
        /// 
        /// </summary>
        public override string ControllerName => "ATestController";

        /// <summary>
        /// 
        /// </summary>
        public ATestController(WcsDbContext wcsDbContext,IBaseConfigService baseConfig, IMapper mapper, ILoggerService logger, AutomaticStorageInfo asrs,
           IMonitorBaseService monitorBaseService, IPathService pathService, IMesBaseService mesBaseService, ILocationService locationService, IMesCommunicateService mesCommunicateService, IPconBaseService pconBaseService, ISrmTaskFinderFactory srmTaskFinderFactory, IHttpContextAccessor httpContextAccessor, ILoggerService loggerService)
           : base(logger, mapper, wcsDbContext)
        {
            _asrs = asrs;
            _pathService = pathService;
            _monitorBaseService = monitorBaseService;
            _mesBaseService = mesBaseService;
            _locationService = locationService;
            _mesCommunicateService = mesCommunicateService;
            _pconBaseService = pconBaseService;
            _srmTaskFinderFactory = srmTaskFinderFactory;
            _httpContextAccessor = httpContextAccessor;
            _loggerService = loggerService;
            _config = baseConfig;
        }

        #endregion



        /// <summary>(测试用)</summary>
        [HttpGet]
        public async Task<IActionResult> TsetAlarm()
        {
            try
            {
                var sw = Stopwatch.StartNew();
                var monitorData = _monitorBaseService.GetMonitorData();
                foreach (var data in monitorData.ErrorBits)
                {
                    var machineName = data.DeviceName.ReName();
                    if (machineName.IsNullOrEmpty())
                    {
                        Console.WriteLine($"{data.DeviceName} has not rename");
                        continue;
                    }
                    else
                    {
                        Console.WriteLine($"{data.DeviceName}, rename = {machineName}");
                    }
                    
                }

                var pcon = _pconBaseService.GetPconPlc("Pcon01");
                foreach(var data in pcon.Pcons.Values)
                {
                    var machineName = data.MachineName.ReName();
                    if (machineName.IsNullOrEmpty())
                    {
                        Console.WriteLine($"pcon-{data.MachineName} has not rename");
                        continue;
                    }
                    else
                    {
                        Console.WriteLine($"pcon-{data.MachineName}, rename = {machineName}");
                    }
                }

                 _asrs.Nodes.Where(x => x.DeviceType == EnumNodeType.srm)
                    .ToList().ForEach(x => 
                    {
                        foreach (var srm in x.SrmPlc.Srms.Values)
                        {
                            var machineName = srm.MachineName.ReName();
                            if (machineName.IsNullOrEmpty())
                            {
                                Console.WriteLine($"srm-{srm.MachineName} has not rename");
                                continue;
                            }
                            else
                            {
                                Console.WriteLine($"srm-{srm.MachineName}, rename = {machineName}");
                            }
                        }
                    });
                sw.Stop();

                return Ok($"success,耗时:{sw.ElapsedMilliseconds}ms");
            }
            catch (Exception)
            {
                return Ok("failure");
            }
        }

        /// <summary>(测试用)</summary>
        [HttpGet]
        public async Task<IActionResult> Tset()
        {
            try
            {
                var sw = Stopwatch.StartNew();

                var mainTasks = _wcsDbContext.MainTasks
                    //.AsNoTracking()
                    //.Where(x => x.TaskStatus == "Delete" && x.MainTaskType != "InventoryTask")
                    //.Where(x => x.TaskStatus == "Delete" && x.MainTaskType != "InventoryTask")
                    //.Where(x => string.IsNullOrEmpty(x.Path))
                    //.OrderBy(x=>x.Id)
                    //.Take(1000)
                    .ToList();


                var body = new TransportJobListReportByWCSMessageBody();

                var t = mainTasks.Select(x => new TRANSPORTJOB()
                {

                    PALLETNAME = x.UnitId,
                    TRANSFERSTATE = x.SrcType == "SHELF" ? "INSTK" : "MOVING",
                    TRANSPORTJOBNAME = x.TaskId,
                    CURRENTMACHINENAME = x.SrcMachine,
                    CURRENTPOSITIONTYPE = x.SrcType,
                    CURRENTPOSITIONNAME = x.SrcPosition,
                    CURRENTZONENAME = x.SrcZone,
                    PRIORITY = x.Priority,
                }).ToList();

                //var list = new TransportJobList()
                //{
                //    TransportJobs = t
                //};
                body.TRANSPORTJOBLIST = t;

                var message = new TransportJobListReportByWCSMessage(body);

                var t1 = XmlHelper.Serialize(message);
                Console.WriteLine(t1);
                //AddMesMessageQueue(message);
                //foreach (var task in tasks)
                //{
                //    task.Path = _pathService.GetPath(task.SrcMachine, task.DesMachine).DefaultPath;
                //}
                //_wcsDbContext.SaveChanges();
                //var s = new DateTime(2023, 9, 10);
                //var e = new DateTime(2023, 9, 15);

                //var list = _wcsDbContext.Set<InterlockLog>().AsNoTracking()
                ////.Where(x => x.CreatedTime >= s && x.CreatedTime <= e)
                //    .Where(x => x.Content.Contains("test1"))

                //    .ToList();

                //var now = DateTime.Now.AddDays(-31);
                //for (int d = 0; d < 30; d++)
                //{
                //    var date = now.AddDays(d);
                //    for (int i = 0; i < 100000; i++)
                //    {
                //        _wcsDbContext.Set<InterlockLog>().Add(new InterlockLog()
                //        {
                //            Content = $"Test{i}",
                //            Direction = i % 2 == 0 ? "PCON >> WCS" : "PCON << WCS",
                //            CreatedTime = date,
                //            MessageName = $"Test{i}",
                //            Receiver = "PCON",
                //            Sender = "WCS",
                //            TransactionId = DateExtension.GetTimestamp(date),
                //        });
                //    }
                //    _wcsDbContext.SaveChanges();

                //}

                sw.Stop();

                return Ok($"success,耗时:{sw.ElapsedMilliseconds}ms");
            }
            catch (Exception)
            {
                return Ok("failure");
            }
        }


        [HttpGet]
        public async Task<IActionResult> TestMileage()
        {
            try
            {
                var plc = _asrs.ConveyorDic["Pcon01"];
                var miles = _asrs.MotorMileages;

                var content = plc.DbInfo.First(x => x.DbNum == 103).Buffer;

                var srm1db = _asrs.SrmDic["SrmPlc01"].DbInfo;
                var srm2db = _asrs.SrmDic["SrmPlc02"].DbInfo;
                var srm1c1content = srm1db.First(x => x.DbName == "c1_mile").Buffer;
                var srm1c2content = srm1db.First(x => x.DbName == "c2_mile").Buffer;
                var srm2c1content = srm2db.First(x => x.DbName == "c1_mile").Buffer;
                var srm2c2content = srm2db.First(x => x.DbName == "c2_mile").Buffer;

                foreach (var m in miles)
                {
                    if (m.DeviceType == "pcon")
                    {
                        m.Update(content);
                    }
                    else
                    {
                        if (m.DeviceType == "SrmPlc01C1")
                        {
                            m.UpdateSrm(srm1c1content);
                        }
                        if (m.DeviceType == "SrmPlc01C2")
                        {
                            m.UpdateSrm(srm1c2content);
                        }
                        if (m.DeviceType == "SrmPlc02C1")
                        {
                            m.UpdateSrm(srm2c1content);
                        }
                        if (m.DeviceType == "SrmPlc02C2")
                        {
                            m.UpdateSrm(srm2c2content);
                        }
                    }
                }

                var a = miles.OrderBy(x => x.MachineName).ThenBy(x => x.PortName).ToList();


                var fileName = Path.Combine(GlobalValue.MilageLogFolder, $"{DateTime.Now:yyyyMMdd}");

                if (!Directory.Exists(GlobalValue.MilageLogFolder))
                {
                    Directory.CreateDirectory(GlobalValue.MilageLogFolder);
                }

                var t = JsonConvert.SerializeObject(a, new JsonSerializerSettings()
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver(),
                    Formatting = Newtonsoft.Json.Formatting.None,
                });
                System.IO.File.WriteAllText(fileName, t);

                return Json(new ForeEndResult(t));
            }
            catch (Exception)
            {
                return Json(ForeEndResult.Fail("error"));
            }
        }



        [HttpGet]
        public async Task<IActionResult> TsetBcrRate()
        {
            try
            {
                return Json(new ForeEndResult(PconBcrRate.BcrRates));
            }
            catch (Exception)
            {
                return Json(ForeEndResult.Fail("error"));
            }
        }
        [HttpPost]
        public async Task<IActionResult> BackTask(int year1,int month1)
        {
            try
            {
                var starttime = new DateTime(year1, month1, 1);
                var endTime = new DateTime(year1, month1+1, 1);
                var maintasks = _wcsDbContext.MainTaskBaks.Where(x => x.CreatedTime >= starttime && x.CreatedTime < endTime);
                var subTaskBaks = _wcsDbContext.SubTaskBaks.Where(x => x.CreatedTime >= starttime && x.CreatedTime < endTime);
                var data = _mapper.Map<List<UIMainTask>>(maintasks);
                var wb = new XSSFWorkbook();
                ISheet st = ExcelHelper.SetSheet(wb, data);
                var path = Path.Combine(GlobalValue.TaskLogFolder, $"{starttime:yyyyMM}月.xlsx");
                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    wb.Write(fs);
                }
                var nfs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read);
                return Ok();
            }
            catch (Exception)
            {
                return Json(ForeEndResult.Fail("error"));
            }
        }

        [HttpPost]
        public async Task<IActionResult> TestTaskHistory1(QueryMainTaskHistoryModel query)
        {
            var sw = Stopwatch.StartNew();
            var queryable = _wcsDbContext.MainTaskBaks
                              .AsQueryable()
                              .AsNoTracking()
                              .Include(d => d.SubTasks)
                              .WhereIf(x => x.SubTasks.Any(s => s.ToLoc.Contains(query.RoutePath)), !string.IsNullOrEmpty(query.RoutePath))
                              .OrderByDescending(d => d.CreatedTime)
                              .VagueWhereOut(query, out int count, out int pageCount)
                              .ToList();

            var dataDtos = _mapper.Map<List<UIMainTask>>(queryable);
            foreach (var data in dataDtos)
            {
                data.SubTasks = data.SubTasks.OrderBy(d => d.TaskSeq).ToList();
            }
            await Console.Out.WriteLineAsync($"TestTaskHistory1:{sw.ElapsedMilliseconds}ms");
            return Json(new ForeEndResult(dataDtos, count, pageCount));
        }

        [HttpPost]
        public async Task<IActionResult> TestTaskHistory2(QueryMainTaskHistoryModel query)
        {
            var sw = Stopwatch.StartNew();
            var queryable = _wcsDbContext.MainTaskBaks
                              .AsQueryable()
                              .AsNoTracking()
                              .WhereIf(x => x.Path.Contains(query.RoutePath), !string.IsNullOrEmpty(query.RoutePath))
                              .OrderByDescending(d => d.CreatedTime)
                              .VagueWhereOut(query, out int count, out int pageCount)
                              .ToList();

            var dataDtos = _mapper.Map<List<UIMainTask>>(queryable);
            //foreach (var data in dataDtos)
            //{
            //    data.SubTasks = data.SubTasks.OrderBy(d => d.TaskSeq).ToList();
            //}
            await Console.Out.WriteLineAsync($"TestTaskHistory2:{sw.ElapsedMilliseconds}ms");
            return Json(new ForeEndResult(dataDtos, count, pageCount));
        }


        [HttpGet(nameof(MachineFrequencyRequest))]
        public IActionResult MachineFrequencyRequest(int frequency)
        {
            _mesCommunicateService.MachineFrequencyRequest("CJSTW100", frequency == 0 ? "LOW" : "HIGH");
            return Ok();
        }


        [HttpGet(nameof(SpacerCarrierChangeRequest))]
        public IActionResult SpacerCarrierChangeRequest()
        {
            _mesCommunicateService.SpacerCarrierChangeRequest("CJMCV600", "CSP050", "6", "1234");
            return Ok();
        }

        [HttpPost]
        public async Task<IActionResult> TestAlarmMsg(string machineName,string errorCode)
        {
            var alarm = GetAlarm(errorCode);
            var errorDetail = alarm.AlarmName;
            if (string.IsNullOrEmpty(alarm.AlarmName)) return Json(ForeEndResult.Fail("")); ;
            var arg = GetAlarmArgs(machineName, errorCode);
            if (!string.IsNullOrEmpty(arg))
            {
                errorDetail = string.Format(alarm.AlarmName, arg);
            }
            var d = new DeviceErrorQueue()
            {
                CreatedTime = DateTime.Now,
                ErrorCode = errorCode,
                ErrorDetail = errorDetail,
                ErrorLevel = alarm.Level.ToString(),
                LastUpdateTime = DateTime.Now,
                MachineName = machineName,
                PortName = machineName,
                PlcName = machineName
            };


            _wcsDbContext.DeviceErrorQueues.Add(d);
            _wcsDbContext.SaveChanges();
            return Json(ForeEndResult.Ok);
        }
        private AlarmExplanation GetAlarm(string errorCode)
       => _wcsDbContext.AlarmExplanations
                  .Where(x => x.Module == "srm")
                  .Where(x => x.Code == errorCode)
                  .FirstOrDefault()
       ?? AlarmExplanation.GetUnkAlarm(errorCode);

        private string GetAlarmArgs(string machineName, string errorCode)
        {
            var isCJSTW100 = machineName == "CJSTW100";
            var arg = "";
            switch (errorCode)
            {
                case "473":
                case "490":
                    arg = isCJSTW100 ? "C1-CJVCV200：36" : "C2-CJVCV400：42";
                    break;
                case "474":
                case "491":
                    arg = isCJSTW100 ? "C1-CJVCV800：35" : "C2-CJVCV300：40";
                    break;
                case "475":
                case "492":
                    arg = isCJSTW100 ? "C1-CJVCV700：28" : "C2-CJVCV200：36";
                    break;
                case "476":
                case "493":
                    arg = isCJSTW100 ? "C1-CJRCV400：8" : "C2-CJVCV100：9";
                    break;
                case "477":
                case "494":
                    arg = isCJSTW100 ? "C1-CJRCV300：6" : "C2-CJRCV200：4";
                    break;
                case "478":
                case "495":
                    arg = isCJSTW100 ? "C1-CJVCV100：9" : "C2-CJRCV100：2";
                    break;
            };

            return arg;
        }
        private T ReadTibcoMessageTestCase<T>(string filePath) where T : BaseTibcoMessage, new()
        {
            var xml = System.IO.File.ReadAllText(filePath);
            var message = XmlHelper.Deserialize<T>(xml);
            message.HEADER.TRANSACTIONID = DateTime.Now.ToString("yyyyMMddHHmmssffffff");
            return message;
        }

        /// <summary>模拟发送栈板箱子绑定关系(测试用)</summary>
        [HttpGet(nameof(SendPalletAndBoxAssignRequest))]
        public async Task<IActionResult> SendPalletAndBoxAssignRequest()
        {
            try
            {
                var message = ReadTibcoMessageTestCase<PalletAndBoxAssignMessage>("TestCase/PalletAndBoxAssignRequest.testcase.xml");
                _mesCommunicateService.PalletAndBoxAssignRequest(message);
                return Ok("success");
            }
            catch (Exception)
            {
                return Ok("failure");
            }
        }

        /// <summary>模拟验证验证实Pallet信息</summary>
        [HttpGet(nameof(SendValidatePalletInputRequest))]
        public async Task<IActionResult> SendValidatePalletInputRequest()
        {
            try
            {
                var xml = System.IO.File.ReadAllText("TestCase/ValidatePalletInputRequest.testcase.xml");
                var message = XmlHelper.Deserialize<ValidatePalletInputMessage>(xml);
                message.HEADER.TRANSACTIONID = DateTime.Now.ToString("yyyyMMddHHmmssffffff");
                _mesCommunicateService.ValidatePalletInputRequest(message);
                return Ok("success");
            }
            catch (Exception ex)
            {
                return Ok("failure");
            }
        }

        /// <summary>模拟发送Pallet的绑定关系</summary>
        [HttpGet(nameof(SendValidatePalletListRequest))]
        public async Task<IActionResult> SendValidatePalletListRequest()
        {
            try
            {
                var xml = System.IO.File.ReadAllText("TestCase/ValidatePalletListRequest.testcase.xml");
                var message = XmlHelper.Deserialize<ValidatePalletListMessage>(xml);
                message.HEADER.TRANSACTIONID = DateTime.Now.ToString("yyyyMMddHHmmssffffff");
                _mesCommunicateService.ValidatePalletListRequest(message);
                return Ok("success");
            }
            catch (Exception)
            {
                return Ok("failure");
            }
        }

        /// <summary>模拟MES下任务</summary>
        [HttpGet(nameof(MesSendJob))]
        public async Task<IActionResult> MesSendJob()
        {
            try
            {
                var str = System.IO.File.ReadAllText("TestCase/PalletRequestTransportJobRequest.testcase.json");
                var body = JsonConvert.DeserializeObject<PalletRequestTransportJobMessageBody>(str);

                var message = new PalletRequestTransportJobMessage(body);

                string xml = XmlHelper.Serialize(message);

                var queueDto = new MesMsgQueueDto()
                {
                    EventName = "PalletRequestTransportJobRequest",
                    TransactionId = message.HEADER.TRANSACTIONID,
                    Content = xml,
                    Return = "",
                    BusinessType = "",
                    RequestType = EnumMesRequestType.Request,
                    Sender = EnumMesMsgSender.MES,
                    Status = EnumMesMsgStatus.MesRequest
                };
                var queue = _mapper.Map<MesMsgQueue>(queueDto);
                _wcsDbContext.MesMsgQueues.Add(queue);
                await _wcsDbContext.SaveChangesAsync();
                return Ok("success");
            }
            catch (Exception)
            {
                return Ok("failure");
            }
        }



        /// <summary>
        /// 测试Inventory功能
        /// </summary>
        [HttpGet(nameof(InventoryZones))]
        public IActionResult InventoryZones()
        {

            try
            {
                var zoneList = _locationService.InventoryZones();
                var pallets = _locationService.InventoryPallets();
                var zoneMessage = new InventoryZoneDataReportMessage(new InventoryZoneDataReportMessageBody("CJSTW100", zoneList));

                var palletMessage = new InventoryPalletDataReportMessage(new InventoryPalletDataReportMessageBody("CJSTW100", pallets));
                var zoneStr = XmlHelper.Serialize(zoneMessage);
                var palletStr = XmlHelper.Serialize(palletMessage);
                return Ok(palletStr);
            }
            catch (Exception ex)
            {
                return Ok(ex.Message);
            }
        }
        /// <summary>
        /// 数据库操作日志添加测试数据
        /// </summary>
        /// <returns></returns>
        [HttpGet(nameof(TestAddOperationLog))]
        public IActionResult TestAddOperationLog()
        {

            for (int i = 1; i < 1000; i++)
            {
                var log = new OperationLog()
                {
                    UserName = "test" + i,
                    Controller = "test" + i,
                    MethodName = "test" + i,
                    UnitId = "test" + i,
                    DeviceName = "test" + i,
                    Remark = "test" + i,
                    CreatedTime = DateTime.Now.AddDays(-90)
                };
                _wcsDbContext.Add(log);
                //var log = _wcsDbContext.OperationLogs.Where(x => x.Id == i).FirstOrDefault();
                //if (log != null)
                //{
                //    _wcsDbContext.OperationLogs.Remove(log);
                //}
                _wcsDbContext.SaveChanges();

            }

            return Ok();
        }

        /// <summary>
        /// 数据库系统日志添加测试数据
        /// </summary>
        /// <returns></returns>
        [HttpGet(nameof(TestAddSystemErrorLog))]
        public IActionResult TestAddSystemErrorLog()
        {

            for (int i = 1; i < 1000; i++)
            {
                var log1 = new SystemErrorLog()
                {
                    Log = "test" + i,
                    CreatedTime = DateTime.Now.AddDays(-90)
                };
                _wcsDbContext.Add(log1);
                //var log = _wcsDbContext.OperationLogs.Where(x => x.Id == i).FirstOrDefault();
                //if (log != null)
                //{
                //    _wcsDbContext.OperationLogs.Remove(log);
                //}
                _wcsDbContext.SaveChanges();

            }

            return Ok();
        }

        /// <summary>
        /// 数据库WCS运行日志添加测试数据
        /// </summary>
        /// <returns></returns>
        [HttpGet(nameof(TestAddWcsRunLog))]
        public IActionResult TestAddWcsRunLog()
        {

            for (int i = 1; i < 1000; i++)
            {
                var log1 = new WcsRunLog()
                {
                    UnitId = "test" + i,
                    MsgValue = "test" + i,
                    CreatedTime = DateTime.Now.AddDays(-90)
                };
                _wcsDbContext.Add(log1);
                //var log = _wcsDbContext.OperationLogs.Where(x => x.Id == i).FirstOrDefault();
                //if (log != null)
                //{
                //    _wcsDbContext.OperationLogs.Remove(log);
                //}
                _wcsDbContext.SaveChanges();

            }

            return Ok();
        }

        [HttpGet(nameof(TestAddLoginLog))]
        public IActionResult TestAddLoginLog()
        {

            for (int i = 1; i < 1000; i++)
            {
                var log1 = new LoginLog()
                {
                    UserName = "test" + i,
                    LoginIP = "test" + i,
                    CreatedTime = DateTime.Now.AddDays(-90)
                };
                _wcsDbContext.Add(log1);
                //var log = _wcsDbContext.OperationLogs.Where(x => x.Id == i).FirstOrDefault();
                //if (log != null)
                //{
                //    _wcsDbContext.OperationLogs.Remove(log);
                //}
                _wcsDbContext.SaveChanges();

            }

            return Ok();
        }

        [HttpGet(nameof(TestAddMesMsgQueueBakLog))]
        public IActionResult TestAddMesMsgQueueBakLog()
        {

            for (int i = 1; i < 1000; i++)
            {
                var log1 = new MesMsgQueueBak()
                {
                    Sender = i,
                    TransactionId = "test" + i,
                    Content = "test" + i,
                    Return= "test" + i,
                    EventName = "test" + i,
                    Status= i,
                    BusinessType="test" + i,
                    RequestType = i,
                    CreatedTime = DateTime.Now.AddDays(-90)
                };
                _wcsDbContext.Add(log1);
                //var log = _wcsDbContext.OperationLogs.Where(x => x.Id == i).FirstOrDefault();
                //if (log != null)
                //{
                //    _wcsDbContext.OperationLogs.Remove(log);
                //}
                _wcsDbContext.SaveChanges();

            }

            return Ok();
        }

        [HttpGet(nameof(TestAddDeviceErrorLog))]
        public IActionResult TestAddDeviceErrorLog()
        {

            for (int i = 1; i < 1000; i++)
            {
                var log1 = new DeviceErrorLog()
                {
                    PlcName = "test"+i,
                    DeviceName = "test" + i,
                    ErrorCode = "test" + i,
                    ErrorDetail = "test" + i,
                    SetTime = "test" + i,
                    IsCsotError = true,
                    CreatedTime = DateTime.Now.AddDays(-90)
                };
                _wcsDbContext.Add(log1);
                //var log = _wcsDbContext.OperationLogs.Where(x => x.Id == i).FirstOrDefault();
                //if (log != null)
                //{
                //    _wcsDbContext.OperationLogs.Remove(log);
                //}
                _wcsDbContext.SaveChanges();

            }

            return Ok();
        }

        [HttpGet(nameof(TestTrigger))]
        public IActionResult TestTrigger()
        {
            var thresholdDate = DateTime.Now.AddDays(0 - 90);

            var expiredLogs = _wcsDbContext.OperationLogs
                           .AsQueryable()
                           .Where(d => d.CreatedTime < thresholdDate)
                           .ToList();
            if (expiredLogs?.Count > 0)
            {
                var wb = new XSSFWorkbook();

                ISheet st = ExcelHelper.SetSheet(wb, expiredLogs);

                var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"logs", "operation_logs", $"{DateTime.Now:yyyyMMdd}.xlsx");
                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    wb.Write(fs);
                }

                //var name = thresholdDate.ToString("yyyyMMdd") + "_OperationLog.xlsx";
                //// 指定Excel文件的保存路径和名称  
                //string excelFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, name);

                //// 保存过期日志到Excel文件  
                //_loggerService.SaveExpiredLogsToExcel(expiredLogs, excelFilePath);
            }
                
            return Ok();
        }
        [HttpPost]
        public async Task<IActionResult> SwitchDir()
        {
            _config.SetConfigMsg("MACHINEDOWNTIME1", "1801");
            return Ok();
        }

        [HttpPost]
        public async Task<IActionResult> recoveryDir()
        {
            var vcv800 = _asrs.Pcons.FirstOrDefault(x => x.MachineName == "CJVCV800" && x.PortName == "01");
            // 恢复时VCV800要切换从入库模式
            if (vcv800.WorkType == 2)
            {
                bool isGoods = vcv800.Machine.Pcons.Any(x => x.IsGoods == 1 || !string.IsNullOrEmpty(x.UnitId));
                bool isTask = _wcsDbContext.SubTasks.Any(x => x.ToLoc == "CJVCV800" && x.TaskStatus == EnumSubTaskStatus.OnProgress.ToString());

                if (!isGoods && !isTask)
                {
                    var pconMsg = new PconSendMsg()
                    {
                        PconName = (ushort)vcv800.PconName,
                        Request = (ushort)EnumPconSendMsg.ChangeInModeCmd
                    };
                    var deviceMsgQueueDto = new DeviceMsgQueueDto(vcv800, pconMsg);

                    var deviceMsgQueue = _mapper.Map<DeviceMsgQueue>(deviceMsgQueueDto);
                    _wcsDbContext.Add(deviceMsgQueue);
                    _wcsDbContext.SaveChanges();
                }
            }
            return Ok();
        }
    }
}
